﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Xml;
using System.IO;
using System.Windows.Forms;

namespace Tsanie.AzerothReader.Util {
    class Config {
        public static readonly string c_AppTitle;
        public static readonly string c_AppPath;
        public static readonly string c_UserAgent;

        public const string c_NgaHost = "http://bbs.ngacn.cc";
        public const string c_178Host = "http://account.178.com";

        private const string c_ConfigFile = "\\Tsanie.AzerothReader.xml";
        private static readonly XmlDocument _config = null;

        static Config() {
            string ver = Assembly.GetExecutingAssembly().GetName().Version.Major + "."
                + Assembly.GetExecutingAssembly().GetName().Version.Minor;
            c_AppTitle = "Azeroth Reader v" + ver + "." + Assembly.GetExecutingAssembly().GetName().Version.Build;
#if beta
            c_AppTitle += " beta";
#endif
            c_AppPath = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
            c_UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ) AppleWebKit/535.1 (KHTML, like Gecko) Safari/535.1 AzerothReader/" + ver;

            _config = new XmlDocument();
            if (!File.Exists(c_AppPath + c_ConfigFile)) {
                CreateConfig();
                _config.Load(c_AppPath + c_ConfigFile);
                return;
            }
            _config.Load(c_AppPath + c_ConfigFile);
            LoadConfig();
        }
        public static void SetValue(string key, object value) {
            FieldInfo fi = typeof(Config).GetField("_" + key, BindingFlags.Static | BindingFlags.NonPublic);
            if (fi == null)
                return;
            string val = (value == null ? null : value.ToString());
            fi.SetValue(null, val);
            XmlNode node = _config.SelectSingleNode("/configuration/" + key);
            if (node == null) {
                node = _config.CreateElement(key);
                node.AppendChild(_config.CreateCDataSection(val));
                _config.SelectSingleNode("/configuration").AppendChild(node);
            } else {
                node.RemoveAll();
                node.AppendChild(_config.CreateCDataSection(val));
            }
            Save();
        }
        public static string GetValue(string key) {
            XmlNode node = _config.SelectSingleNode("/configuration/" + key);
            if (node == null)
                return null;
            string val = (string.IsNullOrEmpty(node.InnerText) ? null : node.InnerText);
            return val;
        }
        private static void Save() {
            _config.Save(c_AppPath + c_ConfigFile);
        }

        public static void LoadConfig() {
            foreach (FieldInfo fi in typeof(Config).GetFields(BindingFlags.Static | BindingFlags.NonPublic)) {
                if (fi.FieldType == typeof(string) && fi.Name[0] == '_') {
                    fi.SetValue(null, GetValue(fi.Name.Substring(1)));
                }
            }
        }
        private static void CreateConfig() {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(c_AppPath + c_ConfigFile, settings);
            writer.WriteStartElement("configuration");
            foreach (FieldInfo fi in typeof(Config).GetFields(BindingFlags.Static | BindingFlags.NonPublic)) {
                if (fi.FieldType != typeof(string) || fi.Name[0] != '_')
                    continue;
                writer.WriteStartElement(fi.Name.Substring(1));
                object obj = fi.GetValue(null);
                writer.WriteCData(obj == null ? null : obj.ToString());
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.Flush();
            writer.Close();
        }

        #region - 配置 -
        /// <summary>
        /// 获取或设置本地Cookie
        /// </summary>
        public static string Cookies {
            get { return _Cookies; }
            set {
                _Cookies = value;
                SetValue("Cookies", value);
            }
        }
        private static string _Cookies = null;
        /// <summary>
        /// 获取或设置超时时间（毫秒为单位）
        /// </summary>
        public static int Timeout {
            get {
                int i;
                if (int.TryParse(_Timeout, out i))
                    return i;
                _Timeout = "15000";
                return 15000;
            }
            set {
                _Timeout = value.ToString();
                SetValue("Timeout", _Timeout);
            }
        }
        private static string _Timeout = "15000";
        /// <summary>
        /// 获取或设置是否记录错误日志
        /// </summary>
        public static bool LogError {
            get {
                bool b;
                if (bool.TryParse(_LogError, out b))
                    return b;
                _LogError = "False";
                return false;
            }
            set {
                _LogError = value.ToString();
                SetValue("LogError", _LogError);
            }
        }
        private static string _LogError = "False";
        #endregion
    }
}
